﻿using CGT.API.Common;
using CGT.API.Models.Order;
using OF.Component.BLL;
using OF.Component.Enum;
using OF.Component.Model;
using OF.Utility;
using OF.Utility.Logging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using OF.Component.DTO;
using System.Data;
using CGT.API.API;

namespace CGT.API.Controllers
{
    /// <summary>
    /// 网办预约单
    /// </summary>
    public class RegOrderController : ApiController
    {
        /// <summary>
        /// 根据用户和业务判断用户是否已经创建订单
        /// </summary>
        /// <param name="userId">用户</param>
        /// <param name="bizTypeId">业务</param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<long> GetOrderId(int userId, int bizTypeId)
        {
            long orderId = NetworkOrderOperate.GetOrderId(userId, bizTypeId);
            return ResultData<long>.Success(orderId);
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <returns></returns>
        public ResultData<long> AddOrder(OrderModel model)
        {
            NetworkOrderInfo order = new NetworkOrderInfo();
            List<NetworkOrderFeeInfo> orderFees = new List<NetworkOrderFeeInfo>();
            decimal orderPrice = 0;
            ModelConvertOrder(order, model);

            //快递费用
            if (order.ExpressFee <= 0)
            {
                var expressFeeInfo = ExpressFeeTplOperate.GetByCompany(order.ExpressCompanyID, order.CityID, order.BizTypeID);
                if (expressFeeInfo == null)
                {
                    return ResultData<long>.Error("获取快递费用失败");
                }
                order.ExpressFee = expressFeeInfo.ExpressFee;
            }
            orderPrice += order.ExpressFee;

            //订单费用
            List<NetWorkFeeConfigInfo> networkFees = NetWorkFeeConfigOperate.GetFeeConfigs(order.CityID, order.BizTypeID);
            foreach (NetWorkFeeConfigInfo item in networkFees)
            {
                if (item.FeeType == 1)
                {
                    order.CostPrice = item.Fee;
                }
                else
                {
                    order.OtherPrice += item.Fee;
                    orderFees.Add(new NetworkOrderFeeInfo() { Fee = item.Fee, FeeName = item.FeeName });
                }
                orderPrice += item.Fee;
            }
            order.OrderPrice = orderPrice;
            order.NeedPayPrice = orderPrice;

            long orderId = NetworkOrderOperate.Insert(order);
            if (orderFees.Count > 0)
            {
                foreach (var item in orderFees)
                {
                    item.OrderID = orderId;
                    NetworkOrderFeeOperate.Insert(item);
                }
            }
            return ResultData<long>.Success(orderId);
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultData<long> UpdateOrder(UpdOrderModel model)
        {
            NetworkOrderInfo order = NetworkOrderOperate.GetByID(model.OrderID);
            ModelConvertOrder(order, model);
            order.UpdatedDate = DateTime.Now;
            NetworkOrderOperate.Update(order);
            return ResultData<long>.Success(model.UserID);
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isComplete"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ResultPageData<List<OrderListModel>> GetOrderList(long userId, int isComplete, int pageSize, int pageIndex)
        {
            ResultPageData<List<OrderListModel>> rt = new ResultPageData<List<OrderListModel>>();
            var condition = new NetworkOrderApiCondition()
            {
                IsComplete = isComplete,
                page = pageIndex,
                rows = pageSize,
                UserID = userId
            };
            DataTable dt = NetworkOrderOperate.GetOrderList(condition);
            List<OrderListModel> list = new List<OrderListModel>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(new OrderListModel()
                {
                    BizTypeID = EConvert.ToInt(row["BizTypeID"]),
                    OrderID = EConvert.ToLong(row["OrderID"]),
                    OrderState = EConvert.ToInt(row["OrderState"]),
                    OrderStateTxt = OrderStateEnumDesc.GetDesc(EConvert.ToInt(row["OrderState"])),
                    UserName = EConvert.ToString(row["UserName"]),
                    CreatedDate = EConvert.ToDateTime(row["CreatedDate"]).ToString("yyyy-MM-dd hh:mm"),
                    OrderPrice = EConvert.ToInt(row["OrderPrice"]),
                    OrderDesc = EConvert.ToString(row["OrderDesc"]),
                    BizTypeName = EConvert.ToString(row["BizTypeName"])
                });
            }
            rt.data = list;
            rt.total = condition.total;
            return rt;
        }

        /// <summary>
        /// 获取审批记录
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<OrderAuditModel>> GetAudit(long orderId)
        {
            List<OrderAuditModel> data = new List<OrderAuditModel>();
            List<NetworkOrderAuditInfo> list = NetworkOrderAuditOperate.GetListByOrder(orderId);
            foreach (NetworkOrderAuditInfo item in list)
            {
                data.Add(new OrderAuditModel()
                {
                    AuditResult = item.AuditResult == 1 ? "通过" : "驳回",
                    CreatedDate = item.CreatedDate.ToString("yyyy-MM-dd HH:MM"),
                    RejectReason = item.RejectReason
                });
            }

            return ResultData<List<OrderAuditModel>>.Success(data);
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<OrderDetailModel> GetOrderDetail(long orderId)
        {
            DataTable dt = NetworkOrderOperate.GetDetailByID(orderId);
            if (dt.Rows.Count > 0)
            {
                OrderDetailModel info = DataRowToModel(dt.Rows[0]);

                var oExist = MailAddressOperate.GetByID(info.MailAddressID);
                if (oExist != null)
                {
                    info.MailModel = new Models.MailAddressOrderModel()
                    {
                        MailAddress = oExist.MailAddress,
                        MailUserMobile = oExist.MailUserMobile,
                        MailUserName = oExist.MailUserName
                    };

                    BaseLocation_AllInfo baseInfo = BaseLocation_AllOperate.GetByID(oExist.MailAddressID);
                    if (baseInfo != null)
                    {
                        info.MailModel.MailAreaAddress = string.Format("{0}{1}{2}", baseInfo.pName, baseInfo.cName, baseInfo.locationName);
                    }
                }
                //获取邮寄信息
                //UserCenterClient usrClient = new UserCenterClient();
                //ResultDataOfResponseMailAddressGet mailResult = usrClient.MailAddress_GetAsync(info.MailAddressID).Result;
                //if (mailResult.Status == 0)
                //{
                //    info.MailModel = new Models.MailAddressOrderModel()
                //    {
                //        MailAddress = mailResult.Data.MailAddress,
                //        MailAreaAddress = mailResult.Data.AreaName,
                //        MailUserMobile = mailResult.Data.MailUserMobile,
                //        MailUserName = mailResult.Data.MailUserName
                //    };
                //}

                return ResultData<OrderDetailModel>.Success(info);
            }
            else
            {
                return ResultData<OrderDetailModel>.Error("参数错误");
            }

        }

        /// <summary>
        /// 身份证识别
        /// </summary>
        /// <returns>身份证识别信息</returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<ResultData<string>> FileUpload()
        {
            // 确定指定的内容是否是 MIME 多部分内容
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            //字段名称
            string fieldName = HttpContext.Current.Request["FieldName"];

            //指定要将文件存入的服务器物理位置  
            string certificatePath = ConfigHelper.GetValue("OrderField.FilePath") + fieldName;
            if (!Directory.Exists(certificatePath))
            {
                Directory.CreateDirectory(certificatePath);
            }
            var provider = new MultipartFormDataStreamProvider(certificatePath);

            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<ResultData<string>>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }
                    //文件保存
                    List<string> files = InnerUploadFile(provider.FileData);
                    string fileName = GetPathFileName(files.FirstOrDefault());
                    return ResultData<string>.Success(GetFieldSrc(fieldName, fileName));
                });
            return task;
        }

        #region 公共

        /// <summary>
        /// 获取图片地址
        /// </summary>
        /// <returns></returns>
        protected string GetFieldSrc(string fieldName, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return "";
            }
            string src = ConfigHelper.GetValue("OrderField.FileSrc");
            return src + fieldName + "/" + fileName;
        }

        /// <summary>
        /// model转订单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="model"></param>
        private void ModelConvertOrder(NetworkOrderInfo order, OrderModel model)
        {
            order.AfterMobile = model.AfterMobile;
            order.AfterPlateNoImage = GetSrcFileName(model.AfterPlateNo);
            order.BeforeMobile = model.BeforeMobile;
            order.BeforePlateNoImage = GetSrcFileName(model.BeforePlateNo);
            order.BizTypeID = model.BizTypeID;
            order.CityID = model.CityID;
            order.CompulsoryImage = GetSrcFileName(model.Compulsory);
            order.DrivingLicenceImage = GetSrcFileName(model.DrivingLicence);
            order.DrivingLicenceBackImage = GetSrcFileName(model.DrivingLicenceBack);
            order.IDNum = model.IDNum;
            order.IsProvince = model.IsProvince;
            order.LicenceClass = model.LicenceClass;
            order.LowLicenceClass = model.LowLicenceClass;
            order.OrderDesc = model.OrderDesc;
            order.OrderState = (int)OrderStateEnum.WaitAudit;
            order.PayState = (int)PayStateEnum.WaitPay;
            order.PlateNo = model.PlateNo;
            order.TemporaryLicenceImage = GetSrcFileName(model.TemporaryLicence);
            order.TemporaryLicenceBackImage = GetSrcFileName(model.TemporaryLicenceBack);
            order.UserID = model.UserID;
            order.UserMobile = model.UserMobile;
            order.UserName = model.UserName;
            order.VIN = model.VIN;
            order.OrderPrice = model.OrderPrice;
            order.CostPrice = model.CostPrice;
            order.OtherPrice = model.OtherPrice;
            order.ExpressFee = model.ExpressFee;
            order.MailAddressID = model.MailAddressID;
            order.ExpressCompanyID = model.ExpressCompanyID;
            order.VehicleLicenceBackImage = GetSrcFileName(model.VehicleLicenceBack);
            order.VehicleLicenceImage = GetSrcFileName(model.VehicleLicence);
            order.HospitalID = model.HospitalID;
            order.CreatedDate = DateTime.Now;
        }

        /// <summary>
        /// 图片保存并返回相应路径
        /// </summary>
        /// <param name="files">文件集合</param>
        /// <returns></returns>
        protected List<string> InnerUploadFile(Collection<MultipartFileData> files)
        {
            List<string> filePaths = new List<string>(files.Count);
            try
            {
                //获取上传文件
                foreach (MultipartFileData file in files)
                {
                    //api默认保存的文件没有后缀名,需要重命名
                    FileInfo f = new FileInfo(file.LocalFileName);
                    int idx = file.Headers.ContentDisposition.FileName.LastIndexOf('.');
                    string pfx = file.Headers.ContentDisposition.FileName.Substring(idx).Replace("\"", string.Empty);
                    //api的文件名,自动添加了双引号(")，此处去掉，否则会提示非法路径。  真坑
                    string newFileName = file.LocalFileName.Replace("-", string.Empty);
                    string newFileNameWithPfx = newFileName + pfx;
                    f.MoveTo(newFileNameWithPfx);
                    filePaths.Add(newFileNameWithPfx);
                }
            }
            catch (Exception ex)
            {
                Log4netLog.Debug(ex.Message);
                Log4netLog.Debug(ex.StackTrace);
                Log4netLog.Debug(ex.Source);
            }
            return filePaths;
        }

        /// <summary>
        /// 获取文件名称
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <returns></returns>
        protected string GetPathFileName(string fullFileName)
        {
            if (string.IsNullOrEmpty(fullFileName))
            {
                return "";
            }
            int idx = fullFileName.LastIndexOf("\\");
            return fullFileName.Substring(idx + 1);
        }

        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="srcFileName"></param>
        /// <returns></returns>
        protected string GetSrcFileName(string srcFileName)
        {
            if (string.IsNullOrEmpty(srcFileName))
            {
                return "";
            }
            //字段名称
            int idx = srcFileName.LastIndexOf("/");
            return srcFileName.Substring(idx + 1);

        }

        /// <summary>
        /// 类型转换
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        protected OrderDetailModel DataRowToModel(DataRow row)
        {
            OrderDetailModel model = new OrderDetailModel();
            model.AfterMobile = EConvert.ToString(row["AfterMobile"]);
            model.AfterPlateNo = GetFieldSrc("AfterPlateNo", EConvert.ToString(row["AfterPlateNoImage"]));
            model.BeforeMobile = EConvert.ToString(row["BeforeMobile"]);
            model.BeforePlateNo = GetFieldSrc("BeforePlateNo", EConvert.ToString(row["BeforePlateNoImage"]));
            model.BizTypeID = EConvert.ToInt(row["BizTypeID"]);
            model.CityID = EConvert.ToInt(row["CityID"]);
            model.Compulsory = GetFieldSrc("Compulsory", EConvert.ToString(row["CompulsoryImage"]));
            model.DrivingLicence = GetFieldSrc("DrivingLicence", EConvert.ToString(row["DrivingLicenceImage"]));
            model.DrivingLicenceBack = GetFieldSrc("DrivingLicenceBack", EConvert.ToString(row["DrivingLicenceBackImage"]));
            model.IDNum = EConvert.ToString(row["IDNum"]);
            model.IsProvince = EConvert.ToInt(row["IsProvince"]);
            model.LicenceClass = EConvert.ToString(row["LicenceClass"]);
            model.LowLicenceClass = EConvert.ToString(row["LowLicenceClass"]);
            model.OrderDesc = EConvert.ToString(row["OrderDesc"]);
            model.OrderStateTxt = OrderStateEnumDesc.GetDesc(EConvert.ToInt(row["OrderState"]));
            //model.PayState = EConvert.ToString(row["PayState"]);
            model.PlateNo = EConvert.ToString(row["PlateNo"]);
            model.TemporaryLicence = GetFieldSrc("TemporaryLicence", EConvert.ToString(row["TemporaryLicenceImage"]));
            model.TemporaryLicenceBack = GetFieldSrc("TemporaryLicenceBack", EConvert.ToString(row["TemporaryLicenceBackImage"]));
            model.UserID = EConvert.ToLong(row["UserID"]);
            model.UserMobile = EConvert.ToString(row["UserMobile"]);
            model.UserName = EConvert.ToString(row["UserName"]);
            model.VIN = EConvert.ToString(row["VIN"]);
            model.OrderPrice = EConvert.ToDecimal(row["OrderPrice"]);
            model.CostPrice = EConvert.ToDecimal(row["CostPrice"]);
            model.MailAddressID = EConvert.ToInt(row["MailAddressID"]);
            model.ExpressCompanyID = EConvert.ToInt(row["ExpressCompanyID"]);
            model.VehicleLicenceBack = GetFieldSrc("VehicleLicenceBack", EConvert.ToString(row["VehicleLicenceBackImage"]));
            model.VehicleLicence = GetFieldSrc("VehicleLicence", EConvert.ToString(row["VehicleLicenceImage"]));
            model.HospitalID = EConvert.ToInt(row["HospitalID"]);
            model.HospitalName = EConvert.ToString(row["HospitalName"]);
            model.BizTypeName = EConvert.ToString(row["BizTypeName"]);
            model.ExpressFee = EConvert.ToDecimal(row["ExpressFee"]);
            return model;
        }
        #endregion
    }
}
